package com.iflyteck.service.impl;

import com.iflyteck.pojo.Comment;
import com.iflyteck.repository.CommentRepository;
import com.iflyteck.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    // value：缓存结果   key：默认在只有一个参数的情况下，key值默认就是方法的参数值，如果没有参数或者多个参数，
    // 会使用SimpleKeyGenerate来生成key
    @Cacheable(cacheNames = "comment",unless = "#result==null")  // 作用：就是将该方法的查询结果存放在SpringBoot的默认缓存中
    // cacheNames： 起一个缓存名称空间  对应缓存唯一标识
    public Comment findCommentById(Integer id) {
        Optional<Comment> optional = commentRepository.findById(id);
        if (!optional.isEmpty()) {
            return optional.get();
        }
        return null;
    }

    // 更新
    @CachePut(cacheNames = "comment",key="#result.id")
    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        return comment;
    }

    // 删除
    @CacheEvict(cacheNames = "comment")
    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
    }

}
